package com.igeek.shop.web.gouwuche;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.igeek.common.utils.PaymentUtil;
import com.igeek.shop.entity.Area;
import com.igeek.shop.entity.Order;
import com.igeek.shop.entity.OrderItem;
import com.igeek.shop.entity.Product;
import com.igeek.shop.entity.User;
import com.igeek.shop.service.ProductService;
import com.igeek.shop.service.gouwuche.CartService;
import com.igeek.shop.service.gouwuche.CartServiceImp;

public class ProductServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private CartService cartservice = new CartServiceImp();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		String state = req.getParameter("state");
		if(state.equals("myOrders")){
			myOrders(req,resp);
		}else if(state.equals("confirmOrder")){
			//确认订单的同时,清空购物车
			confirmOrder(req,resp);
			clearCart1(req,resp);
		}
	
	}

	private void clearCart1(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("user");
		req.getSession().removeAttribute("cart");
		cartservice.clearCart1(user.getUsername());
	}
	private void confirmOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		ProductService service = new ProductService();
		HttpSession session = req.getSession();
		// 表单信息
		Order order = (Order)session.getAttribute("order");
		try {
			BeanUtils.populate(order, req.getParameterMap());

			String pid = (String) req.getSession().getAttribute("pid");    //省id
			String cid = (String) req.getSession().getAttribute("cid");	  //市id
			String aid = (String)  req.getSession().getAttribute("aid");	  //县id
			
			Area province =  cartservice.inquireaddress(pid);    //省地址
			Area city =  cartservice.inquireaddress(cid);				//市地址
			Area area =  cartservice.inquireaddress(aid);			//县地址
			String address = province.getArea_name()+city.getArea_name()+area.getArea_name();
			order.setAddress(address);
			// 1.更新用户的收货信息
			service.updateOrderInfo(order);

			// 2.完成支付功能
			// 获取用户选择的银行
			

			// 获得 支付必须基本数据
			//订单编号
			String orderid = order.getOid();
			//付款
			//String money = order.getTotal()+"";
			String money = "0.01";
			// 银行
			String pd_FrpId = req.getParameter("pd_FrpId");

			// 发给支付公司需要哪些数据
			String p0_Cmd = "Buy";
			String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId");
			String p2_Order = orderid;
			String p3_Amt = money;
			String p4_Cur = "CNY";
			String p5_Pid = "";
			String p6_Pcat = "";
			String p7_Pdesc = "";
			// 支付成功回调地址 ---- 第三方支付公司会访问、用户访问
			// 第三方支付可以访问网址
			String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("callback");
			String p9_SAF = "";
			String pa_MP = "";
			String pr_NeedResponse = "1";
			// 加密hmac 需要密钥
			String keyValue = ResourceBundle.getBundle("merchantInfo").getString("keyValue");
			String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc,
					p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue);
			
			//请易宝支付的地址
			String url = "https://www.yeepay.com/app-merchant-proxy/node?pd_FrpId=" + pd_FrpId + "&p0_Cmd=" + p0_Cmd
					+ "&p1_MerId=" + p1_MerId + "&p2_Order=" + p2_Order + "&p3_Amt=" + p3_Amt + "&p4_Cur=" + p4_Cur
					+ "&p5_Pid=" + p5_Pid + "&p6_Pcat=" + p6_Pcat + "&p7_Pdesc=" + p7_Pdesc + "&p8_Url=" + p8_Url
					+ "&p9_SAF=" + p9_SAF + "&pa_MP=" + pa_MP + "&pr_NeedResponse=" + pr_NeedResponse + "&hmac=" + hmac;

			// 重定向到第三方支付平台
			resp.sendRedirect(url);

			// 3.更新order的状态

		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void myOrders(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpSession session = req.getSession();
		//验证用户是否登录
		User user = (User) session.getAttribute("user");
		if(user == null){
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			return;
		}
		
		ProductService service = new ProductService();
		//如果有用户,查找该用户下的所有订单集合
		List<Order> orderList = service.findAllOrders(user.getUid());
		if(orderList!=null){
			for(Order order : orderList){
				//获取每一个Order对象,根据oid查找对应的List<OrderItem>订单项的集合
				List<Map<String,Object>> listMap = service.findAllOrderItems(order.getOid());
				for(Map<String,Object> map:listMap){
				try {
					OrderItem orderItem = new OrderItem();
					
					//映射orderItem对象
					BeanUtils.populate(orderItem, map);
					Product product = new Product();
					//映射product对象
					BeanUtils.populate(product, map);
					
					//关联两者之间的关系
					orderItem.setProduct(product);
					
					//orderItem存入order的list<orderItem>订单项的集合
					order.getOrderItems().add(orderItem);
					
					
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				}
			}
		}
		//将存入
				req.setAttribute("orderList", orderList);
				//跳转到前台页面
				req.getRequestDispatcher("/order_list.jsp").forward(req, resp);
		
	}

	
	
}
